//
//  CXReconmandViewController.m
//  ProjectOfBStage
//
//  Created by cuixin on 15/11/24.
//  Copyright © 2015年 cuixin. All rights reserved.
//

#import "CXReconmandViewController.h"
#import "CustomerNetworking.h"
//#import "ChannerModel.h"
#import "CXFirstDetailModel.h"
#import "CXFirstDetailCollectionViewCell.h"
#import <MJRefresh.h>
#import "LDY_PlayViewController.h"
#import "CoreDataManager.h"
#import "FZ_Dounment.h"
#define kWidth self.view.frame.size.width
#define kHeight self.view.frame.size.height

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width

#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

#define WIDTH_PRO(X) (X)*(SCREEN_WIDTH/375)

#define HEIGHT_PRO(Y) (Y)*(SCREEN_HEIGHT/667)

@interface CXReconmandViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (nonatomic, retain)NSMutableArray *array;
@property (nonatomic, retain)UICollectionView *collectionView;
@property (nonatomic, assign)NSInteger page;
@property (nonatomic, assign)BOOL loading;
@property (nonatomic, retain)UIView *backView;
@property (nonatomic, retain)NSArray *tempArray;
@property (nonatomic, retain)CoreDataManager *manager;
@end

@implementation CXReconmandViewController

-(void)dealloc{
    [_collectionView release];
    [_array release];
    [_tempArray release];
    [super dealloc];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationController.navigationBar.hidden = NO;
    self.array = [NSMutableArray array];
    self.manager = [CoreDataManager shareManager];
    [self createNavigationBar];
    [self createCollectionView];
    [self header];
    [self footer];
}

-(void)createNavigationBar{
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, HEIGHT_PRO(50))];
    self.backView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.backView];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(WIDTH_PRO(10), HEIGHT_PRO(25), WIDTH_PRO(20), HEIGHT_PRO(20));
    [backButton setBackgroundImage:[UIImage imageNamed:@"gobackbtn@2x"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.backView addSubview:backButton];
    
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH_PRO(150), backButton.frame.origin.y, WIDTH_PRO(100), backButton.frame.size.height)];
    titleLable.font = [UIFont systemFontOfSize:HEIGHT_PRO(14)];
    [titleLable setText:@"推荐列表"];
    [titleLable setTextColor:[UIColor whiteColor]];
    [self.backView addSubview:titleLable];
    
    
    [titleLable release];
    [self.backView release];
}
-(void)backButtonAction:(UIButton *)button{
//    [self.navigationController popViewControllerAnimated:NO];
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)header{
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.page = 1;
        self.loading = NO;
        [self laodData:self.page andLoading:NO];
    }];
    [self.collectionView.header beginRefreshing];
}

-(void)footer{
    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page ++;
        self.loading = YES;
        [self laodData:self.page andLoading:YES];
    }];

}
-(void)laodData:(NSInteger)page andLoading:(BOOL)loading{
    [CustomerNetworking customerWithURL:[NSString stringWithFormat:@"http://echosystem.kibey.com/channel/info?limit=20&id=73&list_order=hot&page=%ld", page] andParamer:nil andBlock:^(id response) {
        if (loading == NO) {
            [self.array removeAllObjects];
        }
        
        for (NSDictionary *dic in [[[response objectForKey:@"result"] objectForKey:@"data"] objectForKey:@"sounds"]) {
            CXFirstDetailModel *model = [CXFirstDetailModel modelWithDictionary:dic];
            [self.array addObject:model];
        }
        [self.collectionView reloadData];
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
    }];
}

-(void)createCollectionView{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, HEIGHT_PRO(60), kWidth, kHeight ) collectionViewLayout:flowLayout];
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = HEIGHT_PRO(5);
    flowLayout.itemSize = CGSizeMake(WIDTH_PRO(179), HEIGHT_PRO(120));
    flowLayout.sectionInset = UIEdgeInsetsMake(0, WIDTH_PRO(5), HEIGHT_PRO(5), WIDTH_PRO(5));
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[CXFirstDetailCollectionViewCell class] forCellWithReuseIdentifier:@"CXRecommandCollectionViewCellId"];
    [flowLayout release];
    [_collectionView release];
    
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.array.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CXFirstDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CXRecommandCollectionViewCellId" forIndexPath:indexPath];
    CXFirstDetailModel *model = [self.array objectAtIndex:indexPath.row];
    cell.detailModel = model;
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [[LDY_PlayViewController sharePlayer] setData:self.array row:indexPath.row];
    LDY_PlayViewController *playController = [LDY_PlayViewController sharePlayer];
    playController.playUrl = [[self.array objectAtIndex:indexPath.row] source];
    playController.name = [[self.array objectAtIndex:indexPath.row] name];
    playController.pic = [[self.array objectAtIndex:indexPath.row] pic];
    playController.allMusicArray = self.array;
    CXFirstDetailModel *model = [self.array objectAtIndex:indexPath.row];

    
    [self searchHistory];
    int count = 0;
    if (self.tempArray.count == 0) {
        FZ_Dounment *list = [NSEntityDescription insertNewObjectForEntityForName:@"FZ_Dounment" inManagedObjectContext:self.manager.managedObjectContext];
        list.name = model.name;
        list.pic = model.pic;
        list.source = model.source;
        [self.manager saveContext];
    }
    else{
        for (FZ_Dounment *modelll in self.tempArray) {
            if (![modelll.source isEqualToString:model.source]) {
                count++;
            }
        }
        if (count == self.tempArray.count) {
            FZ_Dounment *list = [NSEntityDescription insertNewObjectForEntityForName:@"FZ_Dounment" inManagedObjectContext:self.manager.managedObjectContext];
            list.name = model.name;
            list.pic = model.pic;
            list.source = model.source;
            
            [self.manager saveContext];
        }
    }

//    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)searchHistory{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"FZ_Dounment" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"source"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    self.tempArray = fetchedObjects;
    NSLog(@"%@", self.tempArray);
    if (fetchedObjects == nil) {
        
    }else{
        
    }
    
    
}

-(void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
